package com.gxc.blogm.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.servlet.ModelAndView;

import com.gxc.authcore.system.util.CurrentUtil;
import com.gxc.authcore.system.util.ParamUtil;
import com.gxc.blogm.domain.Album;
import com.gxc.blogm.domain.Media;
import com.gxc.blogm.service.AlbumService;
import com.gxc.blogm.service.MediaService;
import com.gxc.dbcore.util.PageInfo;
import com.gxc.dbcore.util.PageList;
import com.gxc.webcore.util.ContextUtil;
import com.gxc.webcore.util.JsonUtil;
import com.gxc.webcore.util.RequestUtil;
import com.gxc.webcore.util.StringUtil;

public class MediaController {

	MediaService mediaService;

	AlbumService albumService;

	public AlbumService getAlbumService() {
		return albumService;
	}

	public void setAlbumService(AlbumService albumService) {
		this.albumService = albumService;
	}

	public MediaService getMediaService() {
		return mediaService;
	}

	public void setMediaService(MediaService mediaService) {
		this.mediaService = mediaService;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView listByAlbum(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String album_id = request.getParameter("album_id");
		Map model = new HashMap();
		Album album = albumService.retrieve(album_id);
		model.put("album", album);
		return new ModelAndView("blogm/media/media_listByAlbum.vm", model);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ModelAndView grid(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map map = RequestUtil.getInMap(request);
		PageInfo pageInfo = PageInfo.getFromRequest(request);
		PageList pageList = mediaService.listPage(map, pageInfo);
		Map result = new HashMap();
		result.put("status", "success");
		result.put("data", pageList);
		String resultString = JsonUtil.object2json(result);
		response.getWriter().write(resultString);
		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ModelAndView create(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String album_id = request.getParameter("album_id");
		Map model = new HashMap();
		Album album = albumService.retrieve(album_id);
		model.put("album", album);
		return new ModelAndView("blogm/media/media_create.vm", model);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView createSave(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map map = new HashMap();
		String media_id = StringUtil.getUUID();
		String fileName = "";
		String newName = "";
		String fileUrl = "";
		String filePath = "";
		String album_id = null;
		String album_name = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			FileItem fileItem = null;
			for (Object item1 : items) {
				FileItem item = (FileItem) item1;
				if (!item.isFormField()) {
					fileItem = item;
				} else if (item.getFieldName().equals("album_id")) {
					album_id = item.getString("UTF-8");
					Album album = albumService.retrieve(album_id);
					album_name = album.getName();
				}
			}
			if (fileItem != null && album_id != null && album_name != null) {
				// 获取上传本地文件的名字不包括其路径
				fileName = fileItem.getName();
				fileName = fileName.substring(fileName
						.lastIndexOf(File.separator) + 1);
				String suffix = "";
				if (fileName.lastIndexOf(".") > 0) {
					suffix = fileName.substring(fileName.lastIndexOf("."));
				}
				newName = media_id + suffix;
				String folderPath = request.getSession().getServletContext()
						.getRealPath("/resources/myblog")
						+ File.separatorChar + album_name;
				File folder = new File(folderPath);
				if (!folder.exists()) {
					folder.mkdirs();
				}
				filePath = folderPath + File.separatorChar + newName;
				File uploadFile = new File(filePath);
				// 将文件保存到服务器
				fileItem.write(uploadFile);
				fileUrl = ParamUtil.get("url_local") + "/resources/myblog"
						+ album_name + "/" + newName;
				map.put("status", "success");
			}
		} catch (Exception e) {
			map.put("status", "failed");
		}

		// 写入数据库
		Media media = new Media();
		media.setId("media_" + media_id);
		media.setAlbum_id(album_id);
		media.setUrl(fileUrl);
		media.setPath(filePath);
		media.setFile_type(1);
		media.setFile_name(newName);
		media.setCreate_user(CurrentUtil.getAuthUser().getId());
		media.setCreate_time(new Date());
		media.setUpdate_time(new Date());
		mediaService.create(media);
		map.put("data", media);

		Map model = new HashMap();
		Album album = albumService.retrieve(album_id);
		model.put("album", album);
		model.put("media", media);
		return new ModelAndView("blogm/media/media_create.vm", model);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView editSave(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		Media media = (Media) RequestUtil.getInObject(request, Media.class);
		media.setUpdate_time(new Date());
		mediaService.update(media);
		result.put("status", "success");
		media = mediaService.retrieve(media.getId());
		result.put("data", media);
		String resultString = JsonUtil.object2json(result);
		response.getWriter().write(resultString);
		return null;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		String id = request.getParameter("id");
		// 将文件文件移至垃圾箱
		Media media = mediaService.retrieve(id);
		File file = new File(media.getPath());
		File trackFolder = new File(ContextUtil.getApplicationRealPath()
				+ "/resources/myblog/blogtrack");
		if (!trackFolder.exists()) {
			trackFolder.mkdirs();
		}
		File newFile = new File(ContextUtil.getApplicationRealPath()
				+ "/resources/myblog/blogtrack/"
				+ media.getPath().substring(media.getPath().lastIndexOf("/")));
		file.renameTo(newFile);
		// 删除数据库中的记录
		int i = mediaService.delete(id);
		result.put("status", "success");
		result.put("data", i);
		String resultString = JsonUtil.object2json(result);
		response.getWriter().write(resultString);
		return null;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView view(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		Media media = mediaService.retrieve(id);
		Map model = new HashMap();
		model.put("media", media);
		return new ModelAndView("blogm/media/media_view.vm", model);
	}

}
